// 格式化时间
// dateFormat("yyyy-MM-dd hh:mm:ss", new Date())
const dateFormat = function (fmt, date) {
  var o = {
    "M+": date.getMonth() + 1,     //月份 
    "d+": date.getDate(),     //日 
    "h+": date.getHours(),     //小时 
    "m+": date.getMinutes(),     //分 
    "s+": date.getSeconds(),     //秒 
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度 
    "S": date.getMilliseconds()    //毫秒 
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}
/*
 * info 信息 va 对象变量 obj 页面Page line 行号
 */
const debug = function (info = null, va = null, obj = null, line = null) {
  let format_time = dateFormat("yyyy-MM-dd hh:mm:ss S", new Date());
  console.info('%c' + format_time + (obj == null ? '' : (' %c' + obj.route)) + (line == null ? '' : (' line:' + line)) + '\n', 'color: blue', obj == null ? '' : 'color: green', info == null ? '' : info, va == null ? '' : va);
}

const ajaxGet = function (url, params = {}, callbackSuccess, callbackError, callbackComplete) {
  wx.getNetworkType({
    success: function (res) {
      if (res.networkType == 'none' || res.networkType == 'unknown') {
        debug('当前网络状态: ', res.networkType);//未连接网络
        wx.showToast({
          title: '请检查网络连接',
          icon: 'none',
          duration: 1500
        });
      }
      else {
        if (typeof params != 'object') {
          params = {};
          debug('request url 参数有误: params');
        }
        // debug('request Url: ', url);
        let dateRequestStartTime = new Date();
        let urlParams = new String(url + '?');
        for (let key in params) {
          urlParams += (key + '=' + params[key] + '&');
        }
        urlParams = urlParams.trim('&');
        wx.request({
          url: url,
          data: params,
          header: {
            'content-type': 'application/x-www-form-urlencoded' // 默认值
          },
          method: 'GET',
          success(res) {
            if (typeof callbackSuccess == 'function') {
              if (res.statusCode == 200) {
                callbackSuccess(res.data);
              }
            }
            debug('数据请求Url: ' + urlParams + '\n数据请求成功: 耗时 ' + parseInt(new Date() - dateRequestStartTime) + ' ms\n', res.data);
          },
          error(res) {
            if (typeof callbackError == 'function') {
              callbackError(res);
            }
            debug('数据请求Url: ' + urlParams + '\n数据请求失败: ', res.errMsg);
          },
          complete(res) {
            if (typeof callbackComplete == 'function') {
              callbackComplete(res);
            }
          }
        });
      }
    },
  })
}

module.exports = {
  dateFormat: dateFormat,
  debug: debug,
  ajaxGet: ajaxGet
}
